package com.aynu.account.tools;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;

@Component
public class ImageUrlTools {
    @Value("${myapp.tempPath}")
    private String TEMP_FILE_PATH;

    public static void main(String[] args) {
        System.out.println(new Date());
    }
    public String getRemoteUrl(String localImageUrl) {
        String remoteUrl = "https://xxxxxxx";
        return localImageUrl.replace("http://centos7:9000", remoteUrl);
    }

    public File downloadImage(String imageUrl, String fileName) {
        try(InputStream in = new URL(imageUrl).openStream()){
            // 创建目标文件路径
//            File file = new File("D:/tmp/img/");
            File file = new File(TEMP_FILE_PATH);
            if (!file.exists() && !file.isDirectory()) {
                System.err.println(file.mkdirs() ? "目录不存在，自动创建目录" : "目录不存在且创建失败");
            }

            Path targetFilePath = Paths.get(TEMP_FILE_PATH + fileName);

            // 将输入流的内容复制到目标文件
            Files.copy(in, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
            in.close();

            return new File(TEMP_FILE_PATH + fileName);
        } catch (IOException e) {
            System.err.println("下载图片时发生错误: " + e.getMessage());
            return null;
        }
    }

//    public static void main(String[] args) {
//        System.out.println(downloadImage("http://centos7:9000/hitch/1721295525644-th.jpg", "tnnd.png"));
//    }

}
